//
// Created by kongkong on 16/9/25.
// Copyright (c) 2016 Kongkong. All rights reserved.
//

#import "KKRequestEngine.h"
#import <AFNetworking/AFHTTPSessionManager.h>
#import "KKRequest.h"

NSString *const baseURL = @"http://139.196.213.159:8088/Fantasia/Public/fantasia/";

@interface KKResponseSerializer : AFJSONResponseSerializer

@end

@implementation KKResponseSerializer

- (BOOL)removesKeysWithNullValues{
    return YES;
}

@end

@interface KKRequestEngine()

@property (nonatomic, strong) AFHTTPSessionManager *requestManager;
@property (nonatomic, strong) NSMutableDictionary *publicHeads;
@end

@implementation KKRequestEngine {

}
+ (KKRequestEngine *)instance {
    static KKRequestEngine *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

- (NSMutableDictionary *)publicHeads{
    @synchronized (self) {
        if (!_publicHeads) {
            _publicHeads = [NSMutableDictionary dictionary];
        }
        return _publicHeads;
    }
}

- (void)setCustomerHead:(NSString *)head forKey:(NSString*)key{
    self.publicHeads[key] = head;
}

- (AFHTTPSessionManager *)requestManager {
    @synchronized (self) {
        if (!_requestManager){
            _requestManager = [AFHTTPSessionManager manager];
            _requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
            _requestManager.responseSerializer = [KKResponseSerializer serializer];
        }
        return _requestManager;
    }
}

+ (id<KKRequestProtocol>)api:(NSString *)api action:(NSString *)action {
    return [KKRequest api:api action:action];
}

- (void)asyncWithRequest:(KKRequest * __nonnull)request completion:(void(^)(KKResponse* __nullable response, id __nullable result))completion{

    NSString *url = [NSString stringWithFormat:@"%@?service=%@.%@",baseURL,request.api,request.action];
    

    void(^Completion)(NSError *,id) = ^(NSError * error,id responseObject){
        
        if (error){
            KKResponse *response = [[KKResponse alloc]init];
            response.error = error;
            completion(response,nil);
        }
        else{
            KKResponse * response = [KKResponse objectWithData:responseObject reflexClass:nil];
            completion(response,response.result);
            //TODO 增加刷新 Token
//            // 登录异常
//            if (1 == response.bizCode) {
//                [[FanUser instance]refreshToken];
//            }
//            else{
//                completion(response,response.result);
//            }
        }
    };

    NSError *serializationError;
    NSMutableURLRequest *mutiRequest = [[AFJSONRequestSerializer serializer] requestWithMethod:@"GET" URLString:url parameters:request.params error:&serializationError];
    if (serializationError) {
        Completion(serializationError,nil);
        return;
    }

    NSString* ts = [NSString stringWithFormat:@"%lld",(long long int)[[NSDate date] timeIntervalSince1970]];
    [mutiRequest setValue:ts forHTTPHeaderField:@"kk_clearts"];

    if (self.publicHeads){
        [self.publicHeads enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([key isKindOfClass:[NSString class]] &&
                    [obj isKindOfClass:[NSString class]]){
                [mutiRequest setValue:obj forHTTPHeaderField:key];
            }
        }];
    }
    NSString *token = [self signWithHeads:mutiRequest.allHTTPHeaderFields params:request.params];
    [mutiRequest setValue:token forHTTPHeaderField:@"kk_sign"];

    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [self.requestManager dataTaskWithRequest:mutiRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        Completion(error,responseObject);
    }];
    [dataTask resume];
}

- (NSString *)signWithHeads:(NSDictionary *)heads params:(NSDictionary *)params{
    NSMutableDictionary *signDic = [NSMutableDictionary dictionary];

    [heads enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([key hasPrefix:@"kk_"]){
            signDic[key] = obj;
        }
    }];

    if (params){
        [signDic addEntriesFromDictionary:params];
    }

    NSArray * keys = [signDic keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if (![obj1 isKindOfClass:[NSString class]] || ![obj2 isKindOfClass:[NSString class]]) {
            return NSOrderedSame;
        }
        return [((NSString *) obj1) compare:((NSString *) obj2)];
    }];

    NSMutableString *signSource = [NSMutableString string];
    for (NSString *key in keys){
        [signSource appendString:signDic[key]];
    }

    return [signSource md5];
}

@end
